package com.time.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.time.vo.ResultVO;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author mjw
 * @date 2022/11/28
 * 处理登录成功时的业务逻辑
 */
//public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//
//    /**
//     * Authentication:携带登录成功时的用户名及角色等信息
//     */
//    @Override
//    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//        Object principal = authentication.getPrincipal();
//        response.setHeader("Content-Type", "application/json;charset=utf-8");
//        PrintWriter writer = response.getWriter();
//        writer.print(new ObjectMapper().writeValueAsString(new ResultVO<>(200, "登录成功", principal)));
//        writer.flush();
//        writer.close();
//    }
//}
public class SecurityAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    /**
     * Authentication:携带登录成功时的用户名及角色等信息
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //直接输出json格式的响应信息
        Object principal = authentication.getPrincipal();
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        //以json格式对外输出身份信息
        ResultVO resultVO = new ResultVO(200, "认证成功", principal);
        out.write(new ObjectMapper().writeValueAsString(resultVO));
        out.flush();
        out.close();
    }
}
